<template>
  <el-card class="mt-20" shadow="hover">
    <el-form inline>
      <el-form-item>
        <el-input v-model="username" placeholder="用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList"
          >查询</el-button
        >
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>
    <div class="mt-10">
      <el-button
        type="primary"
        @click="showAddUser"
        v-if="userInfoStore.buttons.includes('btn.User.add')"
        >添加</el-button
      >
      <el-button
        type="danger"
        :disabled="true"
        v-if="userInfoStore.buttons.includes('btn.User.remove')"
        >批量删除</el-button
      >
    </div>
    <el-table
      :data="userList"
      style="width: 100%"
      border
      class="mt-20"
      :loading="loading"
    >
      <el-table-column type="selection" width="60" />
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="用户名" width="200" prop="username" />
      <el-table-column label="用户昵称" width="200" prop="nickName" />
      <el-table-column label="角色列表" width="200" prop="roleName" />
      <el-table-column label="创建时间" width="200" prop="gmtCreate" />
      <el-table-column label="更新时间" width="200" prop="gmtModified" />
      <el-table-column label="操作" width="200" fixed="right" align="center">
        <template v-slot="{ row }">
          <el-button
            type="info"
            size="small"
            :icon="User"
            title="分配角色"
            @click="showAssignRole(row)"
            v-if="userInfoStore.buttons.includes('btn.User.assgin')"
          />
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            title="修改用户"
            @click="showUpdateUser(row)"
            v-if="userInfoStore.buttons.includes('btn.User.update')"
          />
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="Warning"
            icon-color="#626AEF"
            :title="`你确定要删除 ${row.username}吗?`"
            @confirm="showDeleteUser(row.id)"
          >
            <template #reference>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                title="删除用户"
                v-if="userInfoStore.buttons.includes('btn.User.remove')"
              />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-20"
      :total="total"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      @current-change="getUserList"
      @size-change="getUserList"
      layout="prev,pager,next,jumper,->,sizes,total"
    ></el-pagination>

    <el-dialog
      v-model="addOrUpdateVisible"
      :title="`${addOrUpdateFormData.id ? '修改' : '添加'}用户`"
    >
      <el-form
        :model="addOrUpdateFormData"
        ref="addOrUpdateFormRef"
        :rules="addOrUpdateFormRules"
        label-width="100"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addOrUpdateFormData.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input
            v-model="addOrUpdateFormData.nickName"
            placeholder="请输入用户昵称"
          />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input
            v-model="addOrUpdateFormData.password"
            placeholder="请输入用户密码"
            type="password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addOrUpdateVisible = false">关闭</el-button>
          <el-button type="primary" @click="addOrUpdateUser"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="assignRoleVisible" title="设置用户">
      <el-form
        :model="assignRoleFormData"
        ref="assignRoleFormRef"
        :rules="assignRoleFormRules"
        label-width="100"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="assignRoleFormData.username" disabled />
        </el-form-item>
        <el-form-item label="角色列表" prop="roleId">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="assignRoleFormData.roleId"
            @change="handleCheckedRolesChange"
          >
            <!-- label:选中状态的值（只有在checkbox-group或者绑定对象类型为array时有效） -->
            <el-checkbox
              v-for="role in allRolesList"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="assignRole"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { Search, User, Edit, Delete, Warning } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";
import {
  getUserListApi,
  addUserApi,
  updateUserApi,
  removeUserApi,
  getUserRoleListApi,
  assignUserRoleListApi,
} from "@/api/acl/user";
import type {
  UserList,
  UserItem,
  AddOrUpdateUserFormData,
  RoleList,
} from "@/api/acl/model/userModel";
import { ElMessage } from "element-plus";
import type { CheckboxValueType } from "element-plus";
/*
按钮权限控制
  1.v-if="userInfoStore.buttons.includes('btn.User.remove')"形式
  - 每处应用都要引入pinia数据
  import { useUserInfoStore } from "@/stores/userInfo";
  const userInfoStore = useUserInfoStore();
  - 比较麻烦，每处都要写很长
*/
import { useUserInfoStore } from "@/stores/userInfo";
const userInfoStore = useUserInfoStore();
// 清空
const reset = () => {
  username.value = "";
  getUserList();
};
/******************************* 分配角色 *********************************/
// 表单校验
const assignRoleVisible = ref(false);
const assignRoleFormRef = ref();
const assignRoleFormData = reactive<{
  userId: string;
  roleId: string[];
  username: string;
}>({
  userId: "",
  roleId: [],
  username: "",
});
const assignRoleFormRules = reactive({
  roleId: [{ required: true, message: "请至少选择一个角色" }],
});
// 获取用户角色列表
const showAssignRole = async (row: UserItem) => {
  assignRoleVisible.value = true;
  assignRoleFormData.username = row.username;
  assignRoleFormData.roleId = [];
  assignRoleFormData.userId = row.id;
  assignRoleFormRef.value?.clearValidate();

  const res = await getUserRoleListApi(row.id);
  allRolesList.value = res.allRolesList;
  assignRoleFormData.roleId = res.assignRoles.map((item) => item.id);

  handleCheckedRolesChange();
};
const checkAll = ref(false); // 全选&全不选
const isIndeterminate = ref(false); // 半选
const allRolesList = ref<RoleList>([]);
// 全选&全不选按钮触发的回调
const handleCheckAllChange = (val: CheckboxValueType) => {
  //   checkedCities.value = val ? cities : []
  //   isIndeterminate.value = false
  // console.log(val);
  // checkAll.value = val as boolean;
  if (val) {
    // 全选
    assignRoleFormData.roleId = allRolesList.value.map((role) => role.id);
  } else {
    // 全不选
    assignRoleFormData.roleId = [];
  }
  isIndeterminate.value = false;
};
// 多选框组元素触发的回调
const handleCheckedRolesChange = () => {
  // const checkedCount = value.length
  // checkAll.value = checkedCount === cities.length
  // isIndeterminate.value = checkedCount > 0 && checkedCount < cities.length
  if (assignRoleFormData.roleId.length === 0) {
    // 全不选
    isIndeterminate.value = false;
    checkAll.value = false;
  } else if (assignRoleFormData.roleId.length === allRolesList.value.length) {
    // 全选
    isIndeterminate.value = false;
    checkAll.value = true;
  } else {
    // 半选
    isIndeterminate.value = true;
  }
};
// 保存按钮触发回调
// 根据用户分配角色
const assignRole = async () => {
  await assignRoleFormRef.value.validate();
  await assignUserRoleListApi(
    assignRoleFormData.userId,
    assignRoleFormData.roleId
  );
  assignRoleVisible.value = false;
  ElMessage.success("用户分配角色成功~");
  getUserList();
};
/******************************* 删除用户 *********************************/
const showDeleteUser = async (id: string) => {
  await removeUserApi(id);
  ElMessage.success("删除用户成功~");
  getUserList();
};
/**************************** 添加&修改用户 *********************************/
// 表单校验
const addOrUpdateFormRef = ref();
const addOrUpdateFormData = reactive<AddOrUpdateUserFormData>({
  id: undefined,
  username: "",
  nickName: "",
  password: "",
});
const addOrUpdateFormRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
});

const addOrUpdateVisible = ref(false);
// 添加
const showAddUser = () => {
  addOrUpdateVisible.value = true;
  addOrUpdateFormData.username = "";
  addOrUpdateFormData.nickName = "";
  addOrUpdateFormData.password = "";
  addOrUpdateFormRef.value?.clearValidate();
};
// 修改
const showUpdateUser = (row: UserItem) => {
  addOrUpdateVisible.value = true;
  addOrUpdateFormData.id = row.id;
  addOrUpdateFormData.username = row.username;
  addOrUpdateFormData.nickName = row.nickName;
  addOrUpdateFormData.password = "";
  addOrUpdateFormRef.value?.clearValidate();
};
// 提交
const addOrUpdateUser = async () => {
  await addOrUpdateFormRef.value.validate();
  const id = addOrUpdateFormData.id;
  if (id) {
    // 修改
    await updateUserApi({
      ...addOrUpdateFormData,
      id,
    });
  } else {
    // 添加
    await addUserApi(addOrUpdateFormData);
  }
  addOrUpdateVisible.value = false;
  getUserList();
  ElMessage.success(`${id ? "修改" : "添加"}用户成功~`);
};
/******************************* 分页获取用户列表 ********************************/
const username = ref("");
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);
const loading = ref(false);
const userList = ref<UserList>([]);
// 分页获取用户列表
const getUserList = async () => {
  loading.value = true;
  const res = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
  });
  total.value = res.total;
  userList.value = res.items;
  loading.value = false;
};
onMounted(getUserList);
</script>

<style scoped></style>
